<?php

namespace console\controllers;

use console\components\task\TaskMessageManage;
use console\components\task\TaskTimedManage;
use console\components\task\TimeProcess;
use yii\console\Controller;
use console\components\task\TaskManage;
use yii\helpers\Json;

class TaskkController extends Controller
{
    public function actionIndex()
    {
        $server = new \swoole_server("127.0.0.1", 9505);//swoole提供了两种类型的工人:一种负责请求处理，一种负责执行任务。创建一个server实例
        $server->set([//为server配置参数，设置执行任务工人的数量=4
            'task_worker_num' => '4'
        ]);
        $server->on('Start', [$this, 'onStart']);//将处理器绑定在事件上，将onStart绑定在start事件上，一旦start the server，处理器就会执行
        $server->on('WorkerStart', [$this, 'onWorkerStart']);//将处理器绑定在事件上，将onStart绑定在start事件上，一旦start the server，处理器就会执行
        $server->on('Receive', [$this, 'onReceive']);//所有自定义的协议将定义在onReceive中
        $server->on('Task', [$this, 'onTask']);
        $server->on('Finish', [$this, 'onFinish']);
        $server->start();// start our server, listen on port and ready to accept connections
    }

    public function onStart($server)
    {
        cli_set_process_title('server_master_test');
        echo 'Im on starting[' . \Yii::$app->formatter->asDatetime(time()) . ']' . \SWOOLE_VERSION . " onStart" . PHP_EOL;
    }

    public function onWorkerStart($server,$worker_id)
    {
        swoole_set_process_name("task_worker_test");
        if($worker_id==0){
            $server->tick(60000, function() use ($server) {
                TimeProcess::filterTime();//这一part看不懂啊什么时间啊等等等
            });
            $server->tick(25200000, function () {
                \Yii::$app->db->close();
                echo "DB closed...";
                //\Yii::error('DB closed...');
                \Yii::$app->db->open();
                echo "DB opened...";
                //\Yii::error('DB opened...');
            });
        }
    }

    public function onReceive($server, $fd, $from_id, $data)
    {
        /*\Yii::error('taskkcontroller onreceive datas:');
        \Yii::error($data);*/
        if (TaskManage::checkTask($data)) {
            $server->task($data);
        }
    }

    public function onTask($server, $task_id, $from_id, $data)
    {
        //\Yii::error('taskkcontroller onTask function start...');
        TaskManage::addTask($data);
        $server->finish($data);
    }

    public function onFinish($server, $task_id, $data)
    {
        //\Yii::error('taskkcontroller onFinish function end...');
        echo "Task {$task_id} finish\n";
        echo "Result: {$data}\n";
    }

}
